package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 产生Application的HttpServlet通过Ajax方法调用URL：ajax_create_application<br>
 * 必须登陆：true<br>
 * 必须管理：false<br>
 * 参数：<br>
 * projectId，必须，Application基于的project的ID<br>
 * @author fc
 */
public class AjaxCreateApplication extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		Connection connection = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
			if(loginUser!=null){
				String name = req.getParameter("name");
				int projectId = Integer.parseInt(req.getParameter("projectId"));
				connection = config.getConn();
				int applictionId = CommonQuery.insert_application(connection, projectId, loginUser.getId(), name);
				json.put("type", 0);
				json.put("id",applictionId);
			}else{
				json.put("type", -1);
				json.put("msg", "未登陆");
			}
		}catch (SQLException e) {
			json.put("type", -2);
			json.put("msg", "参数错误");
			e.printStackTrace();
		}catch (Exception e) {
			json.put("type", -3);
			json.put("msg", "未知错误");
			e.printStackTrace();
			Logger.getRootLogger().error(e);
		}finally {
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().error(e);
				}
			}
		}
		resp.getWriter().print(json);
	}
}
